package com.ciei.dpagm.shiro;

import com.alibaba.fastjson.JSONObject;
import com.ciei.dpagm.common.enums.AccessEntranceEnum;
import com.ciei.dpagm.common.token.StatelessToken;
import com.ciei.dpagm.entity.Role;
import com.ciei.dpagm.entity.Users;
import com.ciei.dpagm.service.RightService;
import com.ciei.dpagm.service.RoleService;
import com.ciei.dpagm.service.UserRoleService;
import com.ciei.dpagm.service.UsersService;
import com.ciei.dpagm.util.MemoryData;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.Set;

/**
 * @author wangyan
 * @date 2023/06/07
 */
public class TokenRealm extends AuthorizingRealm {

    @Autowired
    private UsersService usersService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RightService rightService;

    @Autowired
    private UserRoleService userRoleService;

    /**
     * 根据token判断此Authenticator是否使用该realm
     * 必须重写此方法，不然会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof StatelessToken;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        StatelessToken statelessToken = (StatelessToken) authenticationToken;
        String userId = (String) statelessToken.getPrincipal();
        String userName = (String) statelessToken.getCredentials();
        String access = statelessToken.getAccess();
        Integer roleId = AccessEntranceEnum.WPF.getDescription().equals(access) ? Role.SYSTEM_ROLE_ID_ENTERPRISE_EDITION : Role.SYSTEM_ROLE_ID_CENTRAL_CONTROL;
        String loginId = "token:" + userId;
        String cacheRoleId = "role:" + userId;
        Users users;
        if (MemoryData.getSessionIDMap().containsKey(loginId)) {
            users = JSONObject.parseObject(MemoryData.getSessionIDMap().get(loginId),Users.class);
            String userRoleId = MemoryData.getSessionIDMap().get(cacheRoleId);
            if (!String.valueOf(roleId).equals(userRoleId)){
                userRoleService.saveOrUpdate(users.getUserId(), Arrays.asList(roleId));
                MemoryData.getSessionIDMap().put(cacheRoleId, String.valueOf(roleId));
            }
        }else {
            users = usersService.findOneByProperty("loginName",userId);
            if (users == null){
                users = usersService.addUser(userId,userName,roleId);
            }else {
                Set<Integer> roleIds = userRoleService.getRoleIdSet(users.getUserId());
                if (roleIds.size() != 1 || !roleIds.contains(roleId)){
                    userRoleService.saveOrUpdate(users.getUserId(), Arrays.asList(roleId));
                }
            }
            MemoryData.getSessionIDMap().put(loginId, JSONObject.toJSONString(users));
            MemoryData.getSessionIDMap().put(cacheRoleId, String.valueOf(roleId));
        }
        return new SimpleAuthenticationInfo(users,userName,getName());
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Users user = (Users) principals.getPrimaryPrincipal();
        if (user != null) {
            Set<String> roleCodeSet = roleService.getRoleCodeSet(user.getUserId());
            authorizationInfo.setRoles(roleCodeSet);
            Set<String> rightCodeSet = rightService.getRightCodeSet(user.getUserId());
            authorizationInfo.setStringPermissions(rightCodeSet);
        }
        return  authorizationInfo;
    }
}
